
<template>
    <!-- 结算中心/保底值规则配置 -->
    <div class="minimumValueRule">
        <div class="top_operation">
           <div class="top_operation">
            
            <div class="every_operation" v-if="isRegionShow">
                <span><b style="color:red;">*</b> 大区：</span>
                <a-select
                    show-search
                    :filter-option="filterOption"
                    style="width: 195px" 
                    @change="regionChange" 
                    v-model="regionId" 
                    placeholder="请选择大区"
                >
                    <a-select-option :key="index" v-for="(item, index) in regionList" :value="item.id">
                        {{item.name}}
                    </a-select-option>
                </a-select>
            </div>
            <div class="every_operation" v-if="isCityShow">
                <span><b style="color:red;">*</b> 城市：</span>
                <a-select 
                    show-search
                    :filter-option="filterOption"
                    style="width: 195px" 
                    @change="cityChange" 
                    placeholder="请选择城市"
                    v-model="cityId"
                >
                    <a-select-option :key="index" v-for="(item, index) in cityList" :value="item.id">
                        {{item.name}}
                    </a-select-option>
                </a-select>
            </div>
            <div class="every_operation" v-if="isWareShow">
                <span><b style="color:red;">*</b> 仓库：</span>
                <a-select
                    show-search
                    :filter-option="filterOption" 
                    style="width: 195px" 
                    placeholder="请选择仓库"
                    @change="warehouseChange" 
                    v-model="organizeId"
                >
                    <a-select-option :key="index" v-for="(item, index) in warehouseList" :value="item.id">
                        {{item.name}}
                    </a-select-option>
                </a-select>
            </div>
            <div class="every_operation">
                <span>订单类型：</span>
                <a-select style="width: 195px" @change="handleChange" v-model="orderType" allowClear placeholder="请选择订单类型">
                    <a-select-option value="db">
                        调拨
                    </a-select-option>
                    <a-select-option value="hl">
                        合流
                    </a-select-option><a-select-option value="multi">
                        多件
                    </a-select-option><a-select-option value="single">
                        单件    
                    </a-select-option>
                </a-select>
            </div>
            <div class="every_operation">
                <span>客户：</span>
                <a-select style="width: 195px"
                    show-search
                    :filter-option="filterOption"
                    @change="customerChange" 
                    v-model="customerCode" 
                    placeholder="请选择客户"
                    allowClear
                >
                    <a-select-option :key="index" v-for="(item, index) in customerList" :value="item.customerCode">
                        {{item.customerName}}
                    </a-select-option>
                </a-select>
            </div>
            <div class="every_operation">
                <span>货主：</span>
                <a-select style="width: 195px" @change="handleChange" v-model="ownerCode" allowClear placeholder="请选择货主">
                    <a-select-option :key="index" v-for="(item, index) in ownerList" :value="item.ownerCode" >
                            {{item.ownerName}}
                    </a-select-option>
                </a-select>
            </div>
            
            <div class="every_operation">
                <span>项目名称：</span>
                <a-input placeholder="请输入项目名称" v-model="projectName" style="width:195px;" :maxLength="128" allowClear/>
            </div>
            <div class="every_operation" style="margin-top:10px;">
                <span>状态：</span>
                <a-select style="width: 195px" @change="handleChange" v-model="ruleStatus" allowClear  placeholder="请选择状态">
                    <a-select-option value="0">
                        启用
                    </a-select-option>
                    <a-select-option value="1">
                        禁用
                    </a-select-option>
                </a-select>
            </div>
            <div class="every_operation">
                <span>创建时间：</span>
                <a-range-picker
                    v-model="createTime"
                    :show-time="{ format: 'HH:mm:ss' }"
                    format="YYYY-MM-DD HH:mm:ss"
                    :placeholder="['开始 时间', '结束 时间']"
                    @change="createChange"
                    @ok="createOk"
                    style="width:195px;"
                />
            </div>
            <div class="every_operation">
                <span>创建人：</span>
                <a-input placeholder="请输入创建人" v-model="createBy" style="width:195px;" :maxLength="50" allowClear/>
            </div>
            <div class="every_operation">
                <span>修改时间：</span>
                <a-range-picker
                    v-model="updateTime"
                    :show-time="{ format: 'HH:mm:ss' }"
                    format="YYYY-MM-DD HH:mm:ss"
                    :placeholder="['开始 时间', '结束 时间']"
                    @change="editChange"
                    @ok="editOk"
                    style="width:195px;"
                />
            </div>
            <div class="every_operation">
                <span>修改人：</span>
                <a-input placeholder="请输入修改人" v-model="updateBy" style="width:195px;" :maxLength="50" allowClear/>
            </div>
            <div class="every_operation">
                <span>项目备注：</span>
                <a-input placeholder="请输入项目备注" v-model="remark" style="width:195px;" :maxLength="50" allowClear/>
            </div>
            <div class="button_div">
                <a-button type="primary" icon="search" @click="onSearch()">搜索</a-button>
                <a-button type="primary" icon="sync" style="margin-left:20px;" @click="onReset()">重置</a-button>
            </div>
        </div>
    </div>
        <div class="add_btn">
            <a-button type="primary"  @click="addMinimum">新增</a-button>
            <a-button   @click="doExport()" style="margin-left:20px">导出</a-button>
            <a-button style="margin-left:20px;" @click="batchDelete()">删除</a-button>
            <a-button style="margin-left:20px;" @click="doEnable()">启用</a-button>
            <a-button style="margin-left:10px;" @click="doDisable()">禁用</a-button>
            <!-- <a-button style="margin-left:20px;" v-if="deletdBtnShow" @click="batchDelete()" >批量删除</a-button> -->
            <!-- 新增保底值右滑抽屉 -->
            <a-drawer
                :title="drawerTitle"
                :placement="placement"
                :closable="false"
                :visible="visible"
                @close="onClose"
                width="1000"
            >
                <a-form-model
                    ref="ruleForm"
                    :model="form"
                    :rules="rules"
                    layout="inline"
                >
                    <a-form-model-item ref="projectName" label="项目名称" style="width:40%;margin-left:90px" prop="projectName" >
                        <a-input placeholder="请输入项目名称" v-model="form.projectName" style="width:255px"  :maxLength="128" :disabled="btnDisabled" >
                        </a-input>
                    </a-form-model-item>
                    <a-form-model-item ref="customerCode" label="客户"  style="margin-left:100px" prop="customerCode">
                        <a-select 
                            style="width: 267px" 
                            show-search
                            :filter-option="filterOption"
                            @change="formcustomerChange" 
                            v-model="form.customerCode"
                            :disabled="btnDisabled"
                            placeholder="请选择客户"
                        >
                            <a-select-option :key="index" v-for="(item, index) in form.customerList" :value="item.customerCode">
                                {{item.customerName}}
                            </a-select-option>
                        </a-select>
                    </a-form-model-item>
                    <a-form-model-item ref="ownerCode" label="货主"  style="width:40%;margin-left:129px;margin-top:10px" prop="ownerCode"  >
                        <a-select 
                            style="width:255px" 
                            allowClear
                            show-search
                            :filter-option="filterOption"
                            @change="handleChange" 
                            v-model="form.ownerCode"
                            :disabled="btnDisabled"
                            placeholder="请选择货主"
                        >
                            <a-select-option :key="index" v-for="(item, index) in form.ownerlist" :value="item.ownerCode">
                                {{item.ownerName}}
                            </a-select-option>
                        </a-select>
                    </a-form-model-item>
                    <a-form-model-item label="保底方式" style="margin-left:32px;margin-top: 10px" prop="guaranteedWay">
                        <a-radio-group v-model="form.guaranteedWay" @change="guaranteedWayChange"  >
                            <a-radio value="margin_guarantee" :disabled="btnDisabled">
                                余量保底
                            </a-radio>
                            <a-radio value="one_price" :disabled="btnDisabled">
                                一口价
                            </a-radio>
                        </a-radio-group>
                    </a-form-model-item>
                <div style="margin-left:40px;margin-top:14px" :key="index" v-for="(item, index) in form.guaranteedRuleDetails">
                        <div>
                            <span style="padding-left:50px;"><span style="color:red;font-weight:bolder;">* </span>订单类型：</span>
                            <a-select 
                            style="width: 257px" 
                            v-model="item.orderType" 
                            allowClear
                            mode="multiple"
                            @change="handleChange"
                            :disabled="btnDisabled"
                            placeholder="请选择订单类型"
                        >
                            <a-select-option value="db">
                                调拨
                            </a-select-option>
                            <a-select-option value="hl">
                                合流
                            </a-select-option>
                            <a-select-option value="multi">
                                多件
                            </a-select-option>
                            <a-select-option value="single">
                                单件
                            </a-select-option>
                        </a-select>
                            
                            <span style="margin-left:142px"><span style="color:red;font-weight:bolder">*  </span>保底值：
                        <a-input-number placeholder="请输入保底值" v-model="item.guaranteedValue" style="width:195px;" :maxLength="10" :disabled="btnDisabled"  :min="0" :max="2147483647">
                        </a-input-number>
                        <span style="margin-left:8px">
                        <a-select v-model="item.guaranteedUnit" style="width:60px" :disabled="btnDisabled">
                        <a-select-option value="piece"  > 
                                件
                         </a-select-option>
                         <a-select-option value="box">
                                箱
                        </a-select-option>>
                        <a-select-option value="order">
                                单
                        </a-select-option>>
                        </a-select>
                    </span>
                    </span>
                    <div style="margin-top:16px">
                    <span style="margin-left:49px;"><span style="color:red;font-weight:bolder;">* </span>规则价格 :
                        <a-input-number placeholder="请输入规则价格" v-model="item.rulePrice" :maxLength="10" style="width:257px;margin-left:5px" :precision="2" :disabled="btnDisabled" :min="0" :max="2147483647"> 
                        </a-input-number>
                    </span>
                    </div>
                        </div>
                        <div style="width:100%;height:20px;float:left;margin-top:3px;padding-left:130px;">
                            <div style="cursor:pointer;float:left;margin-right:20px;" @click="cutRule(index)" v-if="item.isCutShow">
                                <a-icon type="minus-circle" />
                                <span style="color:#cdcdcd;font-size:14px;">删除规则</span>
                            </div>
                            <div style="cursor:pointer;float:left;" @click="plusRule()" v-if="item.isPlusShow" >
                                <a-icon type="plus-circle" />
                                <span style="color:#cdcdcd;font-size:14px;">添加规则</span>
                            </div>
                        </div>
                    </div>
                </a-form-model>
                <a-form-model layout="inline" >
                <a-form-model-item label="项目备注:" style="margin-left:102px;margin-top:30px">
                    <a-textarea v-model="form.remark" placeholder="请输入" :rows="3" style="width:738px" :maxLength="1024" :disabled="btnDisabled" />
                </a-form-model-item>
                </a-form-model>
                <a-form-model style="margin-top: 40px;">
                    <a-form-model-item :wrapper-col="{ offset: 10 }">
                        <a-button type="primary" @click="modifySubmit" :disabled="btnDisabled" v-if="modify" >
                            修改
                        </a-button>
                        <a-button type="primary" @click="addonSubmit" :disabled="btnDisabled" v-else>
                            保存
                        </a-button>
                        <a-button style="margin-left: 10px;" @click="cancelForm">
                            取消
                        </a-button>
                    </a-form-model-item>
                </a-form-model>
            </a-drawer>
        </div>

        <div class="select_number">
            <span class="number_span">已选择<b>{{selectNumber}}</b>项</span>
            <span class="clear_span" @click="clearSelect">清空</span>
        </div>
        <div class="data_source_list">
            <div class="data_source_details">
                <a-table
                    :loading="tableLoading"
                    :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }" 
                    :columns="columns" 
                    :data-source="data"
                    :pagination="false"
                    bordered
                    rowKey="id"
                    >
                    <span slot="projectName" slot-scope="text, record" href="javascript:;">
                        <a-tooltip placement="topLeft">
                            <template slot="title">
                            <span>{{text}}</span>
                            </template>
                            <span @click="doLook(record)" style="color:#f8ac59;cursor:pointer;">{{text}}</span>
                        </a-tooltip>
                    </span>
                    <span slot="rule" slot-scope="text, record">
                        <a-tooltip placement="topLeft">
                            <template slot="title">
                            <span>{{getRule(record)}}</span>
                            </template>
                            <span>{{getRule(record)}}</span>
                        </a-tooltip>
                    </span>
                    <a slot="action" slot-scope="text, record" href="javascript:;">
                        <span style="margin-right:8px" @click="doEdit(record)">修改</span>
                        <span style="margin-right:8px" @click="showModal(record)">删除</span>
                    </a>
                </a-table>
                <!-- 确认删除对话框 -->
                <a-modal v-model="editVisible" title="确认删除" @ok="handleOk">
                    <p style="text-align:center;">确认删除？</p>
                </a-modal>
                <!-- 导出对话框 -->
                <a-modal
                    title="导出确认"
                    :visible="exportVisible"
                    @ok="exportHandleOk"
                    @cancel="exportHandleCancel"
                >
                    <span>确定导出？</span>
                </a-modal>
                <a-modal
                    title="批量删除"
                    :visible="batchDeleteVisible"
                    @ok="batchDeleteHandleOk"
                    @cancel="batchDeleteHandleCancel"
                > 
                <p style="text-align:center;">确认删除？</p>
                </a-modal>
                <!-- 底部分页组件 -->
                <BottomPagination
                    :total="total"
                    @pageChange="pageChange"
                    @sizeChange="sizeChange"
                ></BottomPagination>
            </div>
        </div>
    </div>
</template>

<script>
    const columns = [
        {
            title: '序号',
            dataIndex: 'index',
            key: 'index',
            align: 'center',
            ellipsis: true,
            width: 80,
            customRender:(taxe,records,index)=>`${index + 1}`
        },
        {
            title: '项目名称',
            dataIndex: 'projectName',
            key: 'projectName',
            scopedSlots: { 
                customRender: 'projectName' 
            },
            align: 'center',
            ellipsis: true,
        },
        {
            title: '客户',
            dataIndex: 'customerCode',
            key: 'customerCode',
            align: 'center',
            ellipsis: true,
        },
        {
            title: '货主',
            dataIndex: 'ownerCode',
            key: 'ownerCode',
            align: 'center',
            ellipsis: true,
        },
        // {
        //     title: '单位',
        //     dataIndex: 'guaranteedRuleDetails[0].guaranteedUnit',
        //     key: 'guaranteedRuleDetails[0].guaranteedUnit',
        //     align: 'center',
        //     ellipsis: true,
        //     customRender: (text, record, index) => {
        //       let re = "";
        //       if (text === 'box') {
        //         re = "箱";
        //       } else if (text === 'piece') {
        //         re = "件";
        //       } else if (text === 'order'){
        //         re = '单';
        //       }
        //         return re;
        //     }
        // },
        {
            title: '保底规则',
            dataIndex: 'rule',
            key: 'rule',
            scopedSlots: { 
                customRender: 'rule' 
            },
            align: 'center',
            ellipsis: true,
            ellipsis: true,
        },
        {
            title: '状态',
            dataIndex: 'ruleStatus',
            key: 'ruleStatus',
            align: 'center',
            ellipsis: true,
            customRender: (text, record, index) => {
              let be = "";
              if (text == '0') {
                be = "启用";
              } else if (text == '1') {
                be = "禁用";
              } 
                return be;
            }
        },
        {
            title: '创建时间',
            dataIndex: 'createTime',
            key: 'createTime',
            align: 'center',
            ellipsis: true,
        },
        {
            title: '创建人',
            dataIndex: 'createBy',
            key: 'createBy',
            align: 'center',
            ellipsis: true,
        },
        {
            title: '修改时间',
            dataIndex: 'updateTime',
            key: 'updateTime',
            align: 'center',
            ellipsis: true,
        },
        {
            title: '修改人',
            dataIndex: 'updateBy',
            key: 'updateBy',
            align: 'center',
            ellipsis: true,
        },
        {
            title: '项目备注',
            dataIndex: 'remark',
            key: 'remark',
            align: 'center',
            ellipsis: true,
        },
        { 
            title: '操作', 
            dataIndex: 'action', 
            key: 'action', 
            scopedSlots: { 
                customRender: 'action' 
            },
            align: 'center',
            width: '140px',
        },
    ];

    import BottomPagination from '../meter/BottomPagination'
    import { getHeadquarters, getRegion, getCity, getWarehouse, getGuaranteedValue, getOwnerName, getCustomerName, putModifySettlement, postMinimumvalue, putEnabledisable,putMinimumuser,getMinimumvalueexport,putMinimumvalue,getMinimumvalue} from '@/api/api'
import { message } from 'ant-design-vue';
    export default {
        name: 'MinimumValueRule',
        components: {
            BottomPagination
        },
        data () {
            return {
                type: '',
                cold:'',
                code: '',
                headquartersId: '', // 总部id
                regionId: undefined, // 大区id
                cityId: undefined, // 城市id
                organizeId: undefined, // 仓库id
                regionList: [],
                cityList: [],
                warehouseList: [],
                regionName: '', // 大区名称
                cityName: '', // 城市名称
                warehouseName: '', // 仓库名称
                ruleId: '',
                customerCode: undefined,
                exportVisible: false, // 导出
                isRegionShow: true,
                createBy: '', // 创建人
                createTime: [], // 创建时间
                updateBy: '', // 修改人
                updateTime: [], // 修改时间
                createTime_begin: '', // 创建时间开始时间
                createTime_end: '', // 创建时间结束时间
                updateTime_begin: '', // 修改时间开始时间
                updateTime_end: '', // 修改时间结束时间
                dateFormat: 'YYYY-MM-DD HH:mm:ss',
                Defaultdisplay:true,
                isCityShow: true,
                isWareShow: true,
                data: [],
                orderType: undefined,
                columns,
                customerList: [],
                ownerList: [],
                ownerCode: undefined,
                remark: '',
                projectName: '',  // 项目名称
                btnDisabled: false,
                tableLoading: false,  
                selectNumber: 0, // 当前选中数据条数
                selectedRowKeys: [], // 当前选择集合
                deletdBtnShow: false, // 批量删除按钮是否显示
                batchDeleteVisible: false,
                pageNo: 1,
                pageSize: 10,
                placement:"right",
                total: 0,
                editVisible: false,
                visible: false,
                modifyvisible: false,
                modify: false,
                guaranteedUnit: '',
                ruleStatus: undefined,
                guaranteedValue: '',
                btnDisabled: false,
                // 删除显示
                Deletesdisplay: false,
                //添加显示
                Showadd: true,
                none: true,
                guaranteedWay: 'margin_guarantee',
                // labelCol: { span: 6 },
                // wrapperCol: { span: 14 },
                form: {
                    city: '',
                    code: '',
                    regionId:'',
                    cityId: '',
                    organizeId: '',
                    name: '',
                    region: '',
                    date1: undefined,
                    guaranteedWay: '',
                    delivery: false,
                    ruleId: '',
                    type: [],
                    projectName: '',
                    resource: '',
                    financeType: '',
                    orderType: '',
                    desc: '',
                    customerCode: [],
                    customerList: [],
                    ownerlist: [],
                    ownerCode: [],
                    Minimumvalue: '',
                    rulePrice: '',
                    projectremarks: '',
                    ids: '',
                    delFlag: '',
                    ruleStatus: '',
                    guaranteedUnit: '',
                    guaranteedValue: '',
                    guaranteedWay: 'margin_guarantee',
                    guaranteedRuleDetails: [
                        {
                            orderType: '',
                            guaranteedValue: '',
                            guaranteedUnit: 'piece',
                            rulePrice: '',
                            sortNo: '',
                            isPlusShow: true,
                            isCutShow: false
                        }
                    ]
                },
                rules: {
                    projectName: [
                        { required: true, message: '请输入项目名称', trigger: 'change', },
                    ],
                    customerCode: [
                        { required: true, message: '请选择客户', trigger: 'change', },
                    ],
                    ownerCode: [
                        { required: false, message: '请选择货主', trigger: 'change', },
                    ],
                    guaranteedWay: [
                        { required: true, message: '请选择保底方式', trigger: 'change', },
                    ],
                    orderType: [
                        { required: true, message: '请选择订单类型', trigger: 'change', },
                    ],
                    minivalue: [
                        { required: true, message: '请输入保底值', trigger: 'change', },
                    ],
                    rulePrices: [
                        { required: true, message: '请输入规则价格', trigger: 'change', },
                    ],
                },
                // 导出
                url: {
                    exportUrl: '/report/guaranteed/rule/exportXls',
                },
                }
            },
        created() {
            this.getHeadquartersList()
        },
        methods: {
            // 选择器
            handleChange(value) {
                console.log(`selected ${value}`);
            },
            // 选择框过滤
            filterOption(input, option) {
                return (
                    option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
                );
            },
            // 创建时间
            createChange(value, dateString) {
                this.createTime = value
                this.createTime_begin = dateString[0]
                this.createTime_end = dateString[1]
            },
            createOk(value) {
                console.log('onOk: ', value);
            },
            // 修改时间
            editChange(value, dateString) {
                this.updateTime = value
                this.updateTime_begin = dateString[0]
                this.updateTime_end = dateString[1] 
            },
            editOk(value) {
                console.log('onOk: ', value);
            },
            
            getRule(record) {
                let aString
                if(record.guaranteedWay == 'margin_guarantee'){
                    aString = '余量保底'
                }else{
                    aString = '一口价'
                };
                
                let orderlist = record.guaranteedRuleDetails.map(item => ({
                    orderType : item.orderType.split(','),
                    guaranteedValue : item.guaranteedValue,
                    rulePrice : item.rulePrice
                }))
                let tos = ''
                let standardString = ''
                if(record.guaranteedRuleDetails.length>=0){
                        orderlist.forEach(item => {
                            if(item.orderType.length == 1){
                                tos = ''
                                item.orderType.forEach(ordertype =>{
                                    if(ordertype == 'db'){
                                        ordertype = '调拨'
                                    }else if(ordertype == 'hl'){
                                        ordertype ='合流'
                                    }else if(ordertype == 'multi'){
                                        ordertype ='多件'
                                    }else if(ordertype == 'single'){
                                        ordertype ='单件'
                                    }
                                    tos = ordertype + '、' 
                                })
                            }
                            if(item.orderType.length > 1){
                                tos = ''
                                item.orderType.forEach(ordertype =>{
                                    if(ordertype == 'db'){
                                        ordertype = '调拨'
                                    }else if(ordertype == 'hl'){
                                        ordertype ='合流'
                                    }else if(ordertype == 'multi'){
                                        ordertype ='多件'
                                    }else if(ordertype == 'single'){
                                        ordertype ='单件'
                                    }
                                    tos += ordertype + '、' 
                                })
                            }
                            standardString += '订单类型:'+tos+';'+'保底值:'+item.guaranteedValue+';'+'规则价格:'+item.rulePrice+';'
                        });  
                }
                return `保底方式:${aString};${standardString}`
            },
            // 批量删除
            batchDelete() {
                this.batchDeleteVisible = true
                this.ids = this.selectedRowKeys.join(',')
            },
            batchDeleteHandleOk(e) {
                let params = {
                    ids: this.ids,
                    ruleStatus: this.ruleStatus
                }
                putMinimumuser(params).then((res)=>{
                    if(res.success){
                        this.batchDeleteVisible = false;
                        this.selectNumber = 0
                        this.selectedRowKeys = []
                        this.deletdBtnShow = false
                        this.getGuaranteedValue()
                        this.$message.success('删除用户成功')
                    }else{
                        this.$message.warning('请选择数据')
                    }
                })
            },
            batchDeleteHandleCancel(e) {
                this.batchDeleteVisible = false;
            },
            // 导出
            doExport(){
                if( this.regionId === '' || this.cityId === '' || this.organizeId === '' ||this.organizeId === undefined ||this.regionId === undefined||this.cityId === undefined){
                    this.$message.warning('导出时必须先选择大区、城市和仓库！')
                    return
                }
                this.exportVisible = true;
                this.ids = this.selectedRowKeys.join(',')
            },
            exportHandleOk(e) {
                this.exportConfirmLoading = true;
                
                let params = {
                    id:this.ids,
                    organizeId: this.organizeId,
                    delFlag: 0
                }
                getMinimumvalueexport(params).then((data)=>{
                    if (!data) {
                        this.$message.warning("文件下载失败")
                        return
                    }
                    if (typeof window.navigator.msSaveBlob !== 'undefined') {
                        window.navigator.msSaveBlob(new Blob([data],{type: 'application/vnd.ms-excel'}), '保底值规则配置'+'.xls')
                    }else{
                        let url = window.URL.createObjectURL(new Blob([data],{type: 'application/vnd.ms-excel'}))
                        let link = document.createElement('a')
                        link.style.display = 'none'
                        link.href = url
                        link.setAttribute('download', '保底值规则配置'+'.xls')
                        document.body.appendChild(link)
                        link.click()
                        document.body.removeChild(link); //下载完成移除元素
                        window.URL.revokeObjectURL(url); //释放掉blob对象
                        this.selectNumber = 0
                        this.selectedRowKeys = []
                        this.deletdBtnShow = false
                        this.exportVisible = false;
                        this.exportConfirmLoading = false;
                    }
                })
            },
            exportHandleCancel(e) {
                this.exportVisible = false;
            },
            // 保底方式
            guaranteedWayChange(e) {
                this.form.guaranteedWay = e.target.value
                console.log(e.target.value);
            },
            // 启用
            doEnable() {
                for(let item of this.selectedRowKeys){
                    for(let items of this.data){
                        if(item == items.id){
                            if(items.ruleStatus == 0){
                                this.$message.warning('当前操作的数据存在已启用的数据！')
                                return
                            }
                        }
                    }
                }
                var Statuss = 0
                this.enableOrDisable(Statuss)
            },

            
            // 禁用
            doDisable() {
                for(let item of this.selectedRowKeys){
                    for(let items of this.data){
                        if(item == items.id){
                            if(items.ruleStatus == 1){
                                this.$message.warning('当前操作的数据存在已禁用的数据！')
                                return
                            }
                        }
                    }
                }
                var Statuss = 1
                this.enableOrDisable(Statuss)
            },
            // 批量启用、禁用
            // enableOrDisable(Statuss) {
            //     this.ids = this.selectedRowKeys.join(',')
            //     let params = {
            //         ids: this.ids,
            //         ruleStatus: Statuss,
            //     }
            //     putEnabledisable(params).then((res)=>{
            //         if(res.success){
            //             this.getGuaranteedValue()
            //             if(Statuss == 0){
            //                 this.$message.success('启用成功！', 6)
            //             }else{
            //                 this.$message.success('禁用成功！', 6)
            //             }
            //         }else{
            //             this.$message.warning('请选择需要启/禁用的项')
            //         }
            //     })
            // },
            // 禁用启用
            enableOrDisable(Statuss) {
                this.ids = this.selectedRowKeys.join(',')
                let params = {
                    ids: this.ids,
                    ruleStatus: Statuss,
                }
                putEnabledisable(params).then((res)=>{
                    if(res.success){
                        this.getGuaranteedValue()
                        if(Statuss == 0){
                            this.$message.success('启用成功！', 6)
                        }else{
                            this.$message.success('禁用成功！', 6)
                        }
                    }else{
                        this.$message.warning('请选择需要启/禁用的项')
                    }
                })
            },

            // 搜索
            onSearch() {
                if( this.regionId === '' || this.regionId === undefined ||this.cityId === '' || this.cityId === undefined || this.organizeId === ''|| this.organizeId === undefined ){
                    this.$message.warning('搜索时必须先选择大区、城市和仓库！')
                }else{
                    this.pageNo = 1
                    // this.getREList()
                     this.getGuaranteedValue()
                }
                this.selectNumber = 0
                this.selectedRowKeys = []
                this.deletdBtnShow = false
            },
            // 重置
            onReset() {
                this.regionId = undefined
                this.cityId = undefined
                this.form.customerCode= ''
                this.form.ownerCode = ''
                this.orderType= undefined
                this.remark= ''
                this.projectName = ''
                this.organizeId = undefined,
                this.cityList = []
                this.ruleStatus= undefined,
                this.createBy= ''
                this.updateBy = ''
                this.form.remark = ''
                this.warehouseList = []
                this.pageSize = 10
                this.pageNo = 1
                this.total = 0
                this.data = []
                this.selectNumber = 0
                this.selectedRowKeys = []
                this.deletdBtnShow = false
                this.customerCode = undefined
                this.customerList = []
                this.ownerCode = undefined
                this.ownerList = []
                this.createTime= []
                this.updateTime= []
                this.createTime_begin = ''
                this.createTime_end = ''
            },
            // 获取总部
            getHeadquartersList(){
                let params = {}
                getHeadquarters(params).then((res)=>{
                    if(res.success){
                        this.headquartersId = res.result.organizeOrgList[0].id
                        this.getRegionList()
                    }
                })
            },
            // 获取大区
            getRegionList(){
                let params = {id: this.headquartersId}
                getRegion(params).then((res)=>{
                    if(res.success){
                        this.regionList = res.result.organizeOrgList
                        if(this.regionList.length === 1){
                            this.regionId = this.regionList[0].id
                            this.getCityList()
                        }
                    }else{
                        this.$message.warning(res.message, 6)
                    }
                })
            },
            // 选择大区
            regionChange(value){
                this.regionId = value 
                this.cityId = undefined
                this.organizeId = undefined
                this.cityList = []
                this.warehouseList = []
                this.getCityList()
                this.customerCode = undefined
                this.customerList = []
                this.ownerCode = undefined
                this.ownerList = []
            },
            // 获取城市
            getCityList(){
                let params = {
                    areaIds: this.regionId
                }
                getCity(params).then((res)=>{
                    if(res.success){
                        this.cityList = res.result.organizeOrgList
                        if(this.cityList.length === 1){
                            this.cityId = this.cityList[0].id
                            this.getWarehouseList()
                        }
                    }
                })
            },
            // 选择城市
            cityChange(value){
                this.cityId = value
                this.organizeId = undefined
                this.warehouseList = []
                this.getWarehouseList()
                this.customerCode = undefined
                this.customerList = []
                this.ownerCode = undefined
                this.ownerList = []
            },
            // 获取仓库
            getWarehouseList(){
                let params = {
                    cityIds: this.cityId
                }
                getWarehouse(params).then((res)=>{
                    if(res.success){
                        this.warehouseList = res.result.organizeOrgList
                        if(this.warehouseList.length === 1){
                            this.organizeId = this.warehouseList[0].id
                            this.code = this.warehouseList[0].code
                            this.getCustomerName()
                        }
                    }
                })
            },
            // 选择仓库
            warehouseChange(value){
                this.organizeId = value
                for(let item of this.warehouseList) {
                    if(item.id === this.organizeId) {
                        this.code = item.code
                        this.customerCode = undefined
                        this.customerList = []
                        this.ownerCode = undefined
                        this.ownerList = []
                        this.getCustomerName()
                    }
                }
            },
            // 获取客户列表
            getCustomerName() {
                let params = {
                    whCode: this.code,
                }
                getCustomerName(params).then((res)=>{
                    if(res.success){
                        this.customerList = res.result
                        this.form.customerList =res.result
                    }else{
                        this.$message.warning(res.message, 6)
                    }
                })
            },
            formcustomerChangeg(){
                let params = {
                    whCode: this.code,
                }
                getCustomerName(params).then((res)=>{
                    if(res.success){
                        this.customerList = res.result
                        this.form.customerList =res.result
                    }else{
                        this.$message.warning(res.message, 6)
                    }
                })
            },
            // 表单获取客户
            formcustomerChange(){
                    let params = {
                        whCode: this.code,
                        customerCode: this.form.customerCode,
                    }
                    // 获取货主
                    getOwnerName(params).then((res)=>{
                        if(res.success){
                            this.form.ownerlist = res.result
                            this.form.ownerCode = undefined
                        }else{
                            this.$message.warning(res.message, 6)
                        }
                    })
            },
            // 选择客户
            customerChange() {
                this.ownerCode = [] 
                if(this.customerCode) {
                    this.getOwnerName()
                }
            },
            // 获取货主名称列表
            getOwnerName() {
                let params = {
                    whCode: this.code,
                    customerCode: this.customerCode,
                }
                getOwnerName(params).then((res)=>{
                    if(res.success){
                        this.ownerList = res.result
                    }else{
                        this.$message.warning(res.message, 6)
                    }
                })
            },
            // 表单获取货主名称
            getOwnerNamelist(){
                
                let params = {
                    whCode : this.code,
                    customerCode : this.form.customerCode
              }
              getOwnerName(params).then((res)=>{
                    if(res.success){
                        this.form.ownerlist = res.result
                    }else{
                        this.$message.warning(res.message, 6)
                    }
                })
            },
            // 获取保底值规则接口（分页）
             getGuaranteedValue() {
                this.tableLoading = true
                let params = {
                    organizeId: this.organizeId,
                    projectName: this.projectName,
                    ruleStatus: this.ruleStatus,
                    createTime_begin: this.createTime_begin,
                    createTime_end: this.createTime_end,
                    updateTime_begin: this.updateTime_begin,
                    updateTime_end: this.updateTime_end,
                    createBy: this.createBy,
                    updateBy: this.updateBy,
                    customerCode: this.customerCode,
                    ownerCode: this.ownerCode,
                    delFlag: 0,
                    pageNo: this.pageNo,
                    pogeSize: this.pageSize,
                    remark: this.remark,
                    orderType:this.orderType
                    // ruleId:this.code
                }
                getGuaranteedValue(params).then((res)=>{
                this.tableLoading = false
                    if(res.success){
                        this.data = res.result.records
                        this.total = res.result.total
                        this.selectNumber = 0
                        this.selectedRowKeys = []
                        this.deletdBtnShow = false
                    }else{
                        this.$message.warning(res.message, 6)
                    }
                })
            },
            // 新增按钮
            addMinimum(){
                if( this.regionId && this.cityId && this.organizeId ){
                    this.visible = true;
                    // 只有验证失败，新增的时候才重置验证状态
                    if(this.validStatus === false) {
                        this.$refs.ruleForm.resetFields()
                    }
                        this.visible = true;
                        this.drawerTitle = '创建保底值规则配置'
                        this.form.guaranteedRuleDetails = [
                            {
                                orderType: [],
                                guaranteedValue: '',
                                guaranteedUnit: 'piece',
                                rulePrice: '',
                                sortNo: '',
                                isPlusShow: true,
                                isCutShow: false
                            }
                        ]
                        this.form.guaranteedWay = ''
                        this.form.projectName = ''
                        this.form.ownerCode = undefined
                        this.form.customerCode = undefined
                        this.form.guaranteedWay= 'margin_guarantee'
                        this.form.orderType = ''
                        this.form.guaranteedUnit = ''
                        this.form.guaranteedPrise = ''
                        this.form.remark = ''
                        this.form.delFlag = ''
                        this.form.createTime = ''
                        this.form.createBy = ''
                        this.form.updateTime = ''
                        this.form.updateBy = ''
                        this.btnDisabled=false
                        this.modify =false
                        this.formcustomerChangeg()
                    }
                    else{
                        this.$message.warning('新增前请选择大区、城市和仓库！')
                    }
                },
            // 选中
            onSelectChange(selectedRowKeys) {
                this.selectedRowKeys = selectedRowKeys
                this.selectNumber = selectedRowKeys.length
                if(this.selectedRowKeys.length > 0){
                    this.deletdBtnShow = true
                }else{
                    this.deletdBtnShow = false
                }
            },
            // 清空选中
            clearSelect() {
                this.selectNumber = 0
                this.selectedRowKeys = []
                this.deletdBtnShow = false
            },
            // 查看
            doLook(record) {
                this.btnDisabled = true

                this.editDrawer(record)
            },
            // 修改
            doEdit(record) {
                this.btnDisabled = false
                this.ruleStatus =''
                this.editDrawer(record)
            },
            // 修改表单用户
            editDrawer(record){
                    // 赋值
                        this.visible = true
                        this.modify =true
                        this.form.ruleStatus = record.ruleStatus
                        this.drawerTitle = '修改保底值规则配置'
                        this.form.projectName=record.projectName
                        this.form.customerCode=record.customerCode
                        this.form.guaranteedWay=record.guaranteedWay
                        this.form.guaranteedPrise=record.guaranteedPrise
                        this.form.remark=record.remark
                        let guaranteedRuleDetailsttt = record.guaranteedRuleDetails.map(item => ({
                        ...item,
                        orderType: item.orderType.split(',')
                        })) 
                        this.form.guaranteedRuleDetails = guaranteedRuleDetailsttt
                        this.setCutPlus()
                        this.getOwnerNamelist()
                        this.form.ownerCode=record.ownerCode ? record.ownerCode.split(','):[]
                        let params= {
                            ruleId : record.id,
                            ruleStatus : record.ruleStatus 
                        }
                        getMinimumvalue(params).then((res => {
                            if(res.success){
                            this.id = record.id
                        }
                        else{
                            this.$message.warning(res.message)
                        }
                    }))
                
            },
            modifySubmit(){
                this.$refs.ruleForm.validate(valid => {
                    if(valid){
                         for(let item of this.form.guaranteedRuleDetails){
                                if( item.orderType == ''){
                                    this.$message.warning('请选择订单类型!')
                                    return
                                } 
                                if( item.rulePrice == '' || item.rulePrice == null|| item.rulePrice == 0){
                                    this.$message.warning('请输入规则价格!')
                                    return
                                }
                                if( item.guaranteedValue == '' || item.guaranteedValue == null || item.guaranteedValue == 0){
                                    this.$message.warning('请输入保底值!')
                                    return
                                }
                            }

                            if(this.form.guaranteedRuleDetails.length > 0){
                                for(let i=0;i<this.form.guaranteedRuleDetails.length;i++){
                                    this.form.guaranteedRuleDetails[i].sortNo = i+1
                                }
                            }
                            let guaranteedRuleDetailst = this.form.guaranteedRuleDetails.map(item => ({
                                ...item,
                                orderType: item.orderType.toString()
                            }))

                            // 传参前将货主进行判断
                            if(this.form.ownerCode == undefined){
                                this.form.ownerCode = ''
                            }
                            let params = {
                                id: this.id,
                                organizeId: this.organizeId,
                                whCode: this.code,
                                ruleStatus :this.form.ruleStatus,
                                customerCode: this.form.customerCode,
                                projectName: this.form.projectName,
                                ownerCode: this.form.ownerCode+'',
                                guaranteedWay: this.form.guaranteedWay,
                                remark: this.form.remark,
                                guaranteedRuleDetails: guaranteedRuleDetailst,
                            }
                            putMinimumvalue(params).then((res)=>{
                                if(res.success){
                                    this.visible = false
                                    this.$message.success('修改成功')
                                    this.getGuaranteedValue()
                                }else{
                                    this.$message.warning(res.message)
                                }
                                this.ruleStatus = undefined
                            })
                        }
                    })
                return false;
            },
            addonSubmit(){
                this.$refs.ruleForm.validate(valid => {
                    if(valid) {
                            for(let item of this.form.guaranteedRuleDetails){
                                if( item.orderType == ''|| item.orderType == undefined){
                                    this.$message.warning('请选择订单类型!')
                                    return
                                } 
                                if( item.rulePrice == '' || item.rulePrice == null|| item.rulePrice == 0 || item.rulePrice ==undefined){
                                    this.$message.warning('请输入规则价格!')
                                    return
                                }
                                if( item.guaranteedValue == '' || item.guaranteedValue == null || item.guaranteedValue == 0|| item.guaranteedValue ==undefined){
                                    this.$message.warning('请输入保底值!')
                                    return
                                }
                            }

                            // 添加sortNo字段
                            if(this.form.guaranteedRuleDetails.length > 0){
                                for(let i=0;i<this.form.guaranteedRuleDetails.length;i++){
                                    this.form.guaranteedRuleDetails[i].sortNo = i+1
                                }
                            }
                            let guaranteedRuleDetails = this.form.guaranteedRuleDetails.map(item => ({
                                ...item,
                                orderType: item.orderType.join(",")
                            }))
                            
                            // 传参前将货主进行判断
                            if(this.form.ownerCode == undefined){
                                this.form.ownerCode = ''
                            }

                            // 新增
                            let params ={
                                whCode: this.code,
                                guaranteedValue:this.form.guaranteedValue,
                                guaranteedUnit:this.form.guaranteedUnit,
                                organizeId: this.organizeId,
                                customerCode: this.form.customerCode,
                                projectName: this.form.projectName,
                                ownerCode: this.form.ownerCode,
                                ruleStatus: 0,
                                remark: this.form.remark,
                                guaranteedWay: this.form.guaranteedWay,
                                guaranteedValue: Number(this.form.guaranteedValue),
                                guaranteedRuleDetails: guaranteedRuleDetails,
                            }
                            postMinimumvalue(params).then((res)=>{
                                if(res.success){
                                    this.visible = false
                                    this.$message.success('添加用户成功')
                                    this.getGuaranteedValue()
                                }else{
                                    this.$message.warning(res.message,6)
                                }
                            })
                    }
                },
            )},
            // 获取当前页数、条数
            pageChange(data1, data2) {
                this.pageNo = data1
                this.pageSize = data2
                this.getGuaranteedValue()

            },
            // 获取当前页数、条数
            sizeChange(data1, data2) {
                this.pageNo = data1
                this.pageSize = data2
                this.getGuaranteedValue()
            },
            // 确认删除对话框
            showModal(record) {
                this.editVisible = true;
                this.ids = record.id
            },
            // 确认删除
            handleOk(e) {
                this.editVisible = false;
                let params = {
                    ids: this.ids,
                    ruleStatus: this.ruleStatus
                }
                putMinimumuser(params).then((res)=>{
                    if(res.success){
                        this.getGuaranteedValue();
                        this.$message.success('删除用户成功')
                    }else{
                        this.$message.warning(res.message)
                    }
                })
            },
            // 添加
            plusRule() {
                this.form.guaranteedRuleDetails.push(
                    {
                        orderType: [],
                        guaranteedRuleId: '',
                        guaranteedUnit: 'piece',
                        rulePrice: '',
                        delFlag: 0,
                    }
                )
                this.setCutPlus()
            },
            cutRule(index){
                this.form.guaranteedRuleDetails.splice(index,1)
                this.setCutPlus()
            },
           // 设置删除和添加按钮显示隐藏
            setCutPlus() {
                let list = this.form.guaranteedRuleDetails
                if(list.length == 1){
                    list[0].isCutShow = false
                    list[0].isPlusShow = true
                }else if(list.length > 1){
                    for(let item of list){
                        item.isCutShow = true
                        item.isPlusShow = false
                    }
                    list[list.length-1].isPlusShow = true
                }
                // 查看时隐藏删除添加按钮
                if(this.btnDisabled == true){
                    for(let item of list){
                        item.isCutShow = false
                        item.isPlusShow = false
                    }          
                }
                this.form.guaranteedRuleDetails = list
            },
            
            onClose() {
                this.visible = false;
            },
            modifydrawer() {
                this.visible = false;
            },
            cancelForm(){
                this.visible = false;
                this.ruleStatus = undefined
            },
            cancelminiForm(){
                this.modifyvisible = false;
            },
            drawerTitle(){

            },
        },
    }
</script>

<style lang="less" scoped>
    .minimumValueRule {
        width: 100%;
        padding: 0 10px 10px 10px;
        font-style: Microsoft YaHei;
        background: #ffffff;
        box-sizing: border-box;
        .top_operation{
            margin-bottom: 10px;
            overflow: hidden;
            .every_operation{
                float: left;
                margin-top: 10px;
                margin-right: 20px;
                span{
                    display: inline-block;
                    width: 85px;
                }
            }
            .button_div{
                float: left;
                margin-top: 10px;
            }
        }
        .select_number{
            width: 100%;
            height: 36px;
            padding-left: 20px;
            margin-bottom: 10px;
            box-sizing: border-box;
            background: rgba(57, 72, 103, .22);
            line-height: 36px;
            .number_span{
                color: #ffffff;
                margin-right: 30px;
                b{
                    color: #394867;
                    margin: 0 15px;
                }
            }
            .clear_span{
                cursor: pointer;
                color: #394867;
            }
        }
        .add_btn{
            margin-bottom: 10px;
        }
        .data_source_list{
            h3{
                font-weight: bold;
            }
            .data_pagination{
                width: 100%;
                height: 32px;
                margin: 20px 0 10px 0;
            }
        }
        .ant-form-inline .ant-form-item{
            margin-right: 4px;
        }
        .dynamic-delete-button {
            cursor: pointer;
            position: relative;
            top: 4px;
            font-size: 24px;
            color: #999;
            transition: all 0.3s;
        }
        .dynamic-delete-button:hover {
            color: #777;
        }
        .dynamic-delete-button[disabled] {
            cursor: not-allowed;
            opacity: 0.5;
        }
    }
</style>
